package com.norra.client.ui

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.switchmaterial.SwitchMaterial
import com.norra.base.api.ApiCallback
import com.norra.base.api.HError
import com.norra.base.api.WebService
import com.norra.base.api.entity.BaseResponse
import com.norra.base.api.entity.Device
import com.norra.base.api.entity.TrashType
import com.norra.base.api.entity.UpdateStatus
import com.norra.client.R
import com.norra.client.model.DeviceEvent
import com.norra.client.viewmodel.DeviceViewModel
import kotlinx.android.synthetic.main.activity_trash.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class TrashActivity : BaseActivity(), View.OnTouchListener {
    private lateinit var device: Device
    private lateinit var viewModel: DeviceViewModel
    private var isSetting = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        device = intent.getSerializableExtra("device") as Device
        setContentView(R.layout.activity_trash)
        setUpToolBar()
        supportActionBar?.title = device.devName
        address.text = device.address

        house_switch.isChecked = device.isNeedCleanHouseHold()
        food_switch.isChecked = device.isNeedCleanFood()
        garden_switch.isChecked = device.isNeedCleanGarden()
        other_switch.isChecked = device.isNeedCleanOther()

        house_switch.tag = TrashType.HOUSE_HOLD
        food_switch.tag = TrashType.FOOD
        garden_switch.tag = TrashType.GARDEN
        other_switch.tag = TrashType.OTHERS

        house_switch.setOnTouchListener(this)
        food_switch.setOnTouchListener(this)
        garden_switch.setOnTouchListener(this)
        other_switch.setOnTouchListener(this)
        viewModel = ViewModelProvider(this).get(DeviceViewModel::class.java)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onEvent(event: DeviceEvent) {
        if (event.type == DeviceEvent.DELETE) {
            finish()
        }
    }

    private fun setStatus(type: String, isOpen: Boolean, switch: SwitchMaterial) {
        if (isSetting) {
            return
        }
        isSetting = true
        showLoadingView()
        val status = if (isOpen) 1 else 0
        val request = UpdateStatus()
        request.devName = device.devName
        request.status = status
        request.model = type
        WebService.get().setVillaDeviceStatus(request).enqueue(object : ApiCallback<BaseResponse> {
            override fun onSuccess(response: BaseResponse) {
                hideLoadingView()
                isSetting = false
                switch.isChecked = isOpen
                updateStatus(type, status)
                sendUpdateEvent()
            }

            override fun onError(error: HError) {
                hideLoadingView()
                isSetting = false
            }

        })
    }

    private fun updateStatus(type: String, status: Int) {
        when (type) {
            TrashType.HOUSE_HOLD -> {
                device.status!![0] = status
            }
            TrashType.FOOD -> {
                device.status!![1] = status
            }
            TrashType.GARDEN -> {
                device.status!![2] = status
            }
            TrashType.OTHERS -> {
                device.status!![3] = status
            }
        }
    }

    private fun sendUpdateEvent() {
        val event = DeviceEvent()
        event.type = DeviceEvent.UPDATE
        event.devName = device.devName
        event.device = device
        EventBus.getDefault().post(event)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_edit, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val intent = Intent(this, AddDeviceActivity::class.java)
        intent.putExtra("is_edit", true)
        intent.putExtra("device", device)
        startActivity(intent)
        return super.onOptionsItemSelected(item)
    }


    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        if (v !is SwitchMaterial) {
            return true
        }
        if (event?.actionMasked == MotionEvent.ACTION_UP) {
            val tag = v.tag as String
            setStatus(tag, !v.isChecked, v)
        }
        return true
    }
}